package sql

import (
	"sdn-executor/config"
	"sdn-executor/utils/loggers"
	"time"

	"github.com/kataras/golog"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// NewSQLDB 创建SQL数据库客户端实例
func NewSQLDB(conf *config.SQLDBConfig, dsn string) (*gorm.DB, error) {
	newLogger := logger.New(
		&loggers.Writer{},
		logger.Config{
			SlowThreshold:             200 * time.Millisecond,     // Slow SQL threshold
			LogLevel:                  getLogLevel(conf.LogLevel), // Log level
			IgnoreRecordNotFoundError: true,                       // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,                      // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		golog.Errorf("Failed open drds. conf:%+v, dsn: %s, err: %v", conf, dsn, err)
		return nil, err
	}
	sqldb, err := db.DB()
	if err != nil {
		golog.Errorf("Failed create drds gorm.db.DB. conf:%+v, err: %v", conf, err)
		return nil, err
	}

	sqldb.SetConnMaxIdleTime(time.Second * time.Duration(conf.MaxIdleTime))
	sqldb.SetConnMaxLifetime(time.Second * time.Duration(conf.MaxLifeTime))
	sqldb.SetMaxIdleConns(conf.MaxIdleConn)
	sqldb.SetMaxOpenConns(conf.MaxOpenConn)

	return db, nil
}

// getLogLevel 根据字符串获取对应的日志级别，默认为 warn，如果不在指定范围内则返回 warn
func getLogLevel(level string) logger.LogLevel {
	logLevel := logger.Warn
	switch level {
	case "info":
		logLevel = logger.Info
	case "warn":
		logLevel = logger.Warn
	case "error":
		logLevel = logger.Error
	case "silent":
		logLevel = logger.Silent
	default:
		logLevel = logger.Warn
	}
	return logLevel
}
